import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// 创建ajax请求对象
const chatroom_service = axios.create({
  baseURL: 'http://localhost:8081',
  timeout: 5000
})

chatroom_service.interceptors.request.use(
  config => {
    if (store.getters.token) { // 判断前端Cookie中是否存在token
      // 让每个请求携带token-- ['Authorization']  key - value
      config.headers['Authorization'] = getToken()
    }
    return config
  },

  error => {
    // 拦截失败操作
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

chatroom_service.interceptors.response.use(
  response => {
    // 获取请求返回数据
    const res = response.data

    // 如果code不等于200，则提示错误信息
    if (res.code !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 如果code为“token失效”或“未携带token”状态码 ，则重新登录（刷新token，刷新页面)
      if (res.code === 10002 || res.code === 99999) {
        // 重新登录（刷新token，刷新页面)
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },

  // 拦截响应失败
  error => {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 创建GET请求
export function getActionByChatroom(url, data) {
  return chatroom_service({
    url: url,
    method: 'get',
    params: data
  })
}

// 创建POST请求
export function postActionByChatroom(url, data) {
  return chatroom_service({
    url: url,
    method: 'post',
    data: data
  })
}

// 创建PUT请求
export function putActionByChatroom(url, data) {
  return chatroom_service({
    url: url,
    method: 'put',
    data: data
  })
}

// 创建DELETE请求
export function deleteActionByChatroom(url, data) {
  return chatroom_service({
    url: url + `/${data}.do`,
    method: 'delete'
  })
}
